// MyThread.cpp: implementation of the CMyThread class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Waving Hands.h"
#include "MyThread.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

extern DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
	CMyThread *pMyThread=(CMyThread *)lpParameter;
	return pMyThread->ThreadFunc();
}


CMyThread::CMyThread()
{
	m_bTerminated=FALSE;
	m_hThread=NULL;
}

CMyThread::~CMyThread()
{
   Terminate(FALSE);
}

BOOL CMyThread::Execute()
{
	if (m_hThread)
	{
		return FALSE;
	}
	m_hThread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadProc,this,0,&m_dwID);
    return (m_hThread==NULL)?FALSE:TRUE;
}

DWORD CMyThread::Terminate(BOOL bCritical)
{
	if (m_hThread==NULL)
		return (DWORD)-1;
	m_bTerminated=TRUE;
	DWORD dwExitCode;
	if (!bCritical)
	{
		for(int i=10;i>0;i--)
		{
			GetExitCodeThread(m_hThread,&dwExitCode);
			if (dwExitCode==STILL_ACTIVE)
				Sleep(25);
			else
				break;
		}
	}
	GetExitCodeThread(m_hThread,&dwExitCode);
	if (dwExitCode==STILL_ACTIVE)
		TerminateThread(m_hThread,-1);
	GetExitCodeThread(m_hThread,&dwExitCode);
	CloseHandle(m_hThread);
	m_hThread=NULL;
	m_bTerminated=FALSE;
	return dwExitCode;
}

